package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常处理类
 * @author jialiangming
 * @create 2020-11-17 14:30
 */
@Slf4j
/*@ResponseBody //以json格式跑出去
@ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")*/
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    /**
     * 由controller抛出的异常就会来到这里
     * @param e
     */
    @ExceptionHandler(value=MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        //1、获取校验的结果
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> map=new HashMap<String,String>();
        bindingResult.getFieldErrors().forEach((item)->{
            //获取到错误提示
            String defaultMessage = item.getDefaultMessage();
            //获取到错误的属性的名字
            String field = item.getField();
            map.put(field,defaultMessage);
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 能够处理任意类型的异常
     * @return
     */
    @ExceptionHandler(value=Throwable.class)
    public R handleException(Throwable throwable){
        log.error("错误：",throwable);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }

}
